package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.BaseCommonUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.IntegrationCashCouponWallet;
import com.rockcent.mall.lib.domain.IntegrationChannel;
import com.rockcent.mall.lib.domain.IntegrationCouponWallet;
import com.rockcent.mall.lib.dto.IntegrationCashCouponWalletDto;
import com.rockcent.mall.lib.dto.IntegrationChannelDto;
import com.rockcent.mall.lib.dto.IntegrationCouponWalletDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.IntegrationChannelRepository;
import com.rockcent.mall.lib.repository.MerchantCouponRepository;
import com.rockcent.service.IntegrationCashCouponWalletSrv;
import com.rockcent.service.MallCashCouponSrv;
import com.rockcent.service.IntegrationChannelSrv;
import com.rockcent.service.IntegrationCouponWalletSrv;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/12/17.
 * 积分渠道管理
 */
@RestController
public class IntegrationChannelController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(IntegrationChannelController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private IntegrationChannelRepository integrationChannelRepository;

    @Autowired
    private IntegrationCashCouponWalletSrv integrationCashCouponWalletSrv;

    @Autowired
    private IntegrationCouponWalletSrv integrationCouponWalletSrv;

    @Autowired
    private IntegrationChannelSrv integrationChannelSrv;

    @Autowired
    private MallCashCouponSrv mallCashCouponSrvImpl;

    @Autowired
    private MerchantCouponRepository merchantCouponRepository;

    /**
     * @api {post} /mall/integration/channel/save M端 积分渠道管理 新建
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} name 渠道名称
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_SAVE, method = RequestMethod.POST)
    public JsonResult integrationChannelSave(@RequestBody IntegrationChannelDto dto,HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String name = dto.getName();
            if (StringUtils.isBlank(name)) {
                jsonResult.remind("渠道名称不能为空",log);
                return;
            }

            IntegrationChannel channelDb = integrationChannelRepository.findTop1ByName(name);
            if (null!=channelDb) {
                jsonResult.remind("渠道名称已存在",log);
                return;
            }
            IntegrationChannel channel = new IntegrationChannel();
            channel.setMallId(userInfoDto.mall.getId());
            channel.setName(name);
            channel = integrationChannelRepository.save(channel);
            //生成渠道appKey前缀 + 渠道ID + 六位随机数
            channel.setAppKey(IntegrationChannel.ROCK_CENT_APP_KEY + String.valueOf(channel.getId()) + BaseCommonUtils.getRandom6());
            integrationChannelRepository.save(channel);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/integration/channel/list M端 积分渠道管理 列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccess {long} id 渠道ID
     * @apiSuccess {String} name 渠道名称
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":[
     *         {
     *             "id":2,
     *             "name":"广发"
     *         }
     *     ]
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_LIST, method = RequestMethod.GET)
    public JsonResult integrationChannelList(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<IntegrationChannel> integrationChannelList = integrationChannelRepository.findByMallIdAndIsDelete(userInfoDto.mall.getId(), Whether.NO);
            jsonResult.data = integrationChannelList;
        };
        return doing.go(request, log);
    }



    /**
     * @api {get} /mall/integration/channel/page M端 积分渠道统计
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} name 渠道名称
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":5,
     *                 "mallId":51,
     *                 "name":"广发证券",
     *                 "cashWallet":{
     *                     "version":0,
     *                     "exchangeNum":3,
     *                     "receiveNum":4,
     *                     "useNum":3
     *                 },
     *                 "couponWallet":{
     *                     "version":0
     *                 }
     *             }
     *         ],
     *         "totalCount":1,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10,
     *         "url":"/mall/integration/channel/page",
     *         "prevUrl":"/mall/integration/channel/page?pageNo=0&pageSize=10",
     *         "nextUrl":"/mall/integration/channel/page?pageNo=0&pageSize=10"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_PAGE, method = RequestMethod.GET)
    public JsonResult qrIntegrationChannelPage(HttpServletRequest request, IntegrationChannelDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            Long mallId = userInfoDto.mall.getId();
            PageResult page = this.getPage(dto.getPageNo(), dto.getPageSize());
            PageResult<IntegrationChannelDto> pageResult = integrationChannelSrv.findByNameAndMallIdAndIsDelete(dto.getName(), mallId, Whether.NO, page);

            pageResult.data.stream().map(channelDtoDto -> {
                Long integrationChannelId = channelDtoDto.getId();

                IntegrationCashCouponWallet cashWallet = integrationCashCouponWalletSrv.caculateCash(null, integrationChannelId, mallId);
                IntegrationCouponWallet couponWallet = integrationCouponWalletSrv.caculateCoupon(null, integrationChannelId, mallId);
                if(cashWallet!=null){
                    Long totalNumCashWallet = mallCashCouponSrvImpl.queryTotalNumByChannelId(integrationChannelId);
                    cashWallet.setTotalNum(totalNumCashWallet);
                }
                if(couponWallet!=null){
                    Long totalNumCouponWallet = merchantCouponRepository.queryTotalNum(integrationChannelId);
                    couponWallet.setTotalNum(totalNumCouponWallet);
                }
                channelDtoDto.setCashWallet(cashWallet);
                channelDtoDto.setCouponWallet(couponWallet);
                return channelDtoDto;

            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MALL_INTEGRATION_CHANNEL_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/export M端 导出积分渠道统计 列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} name <code>可选参数</code> 渠道名称
     * @apiSuccessExample {json} Success-Response:
     * {}
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_EXPORT, method = RequestMethod.GET)
    public JsonResult exportIntegrationChannelPage(HttpServletRequest request, HttpServletResponse response,IntegrationChannelDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            Long mallId = userInfoDto.mall.getId();
            PageResult page = this.getPage(dto.getPageNo(), Integer.MAX_VALUE);
            PageResult<IntegrationChannelDto> pageResult = integrationChannelSrv.findByNameAndMallIdAndIsDelete(dto.getName(), mallId, Whether.NO, page);

            pageResult.data.stream().map(channelDtoDto -> {
                Long integrationChannelId = channelDtoDto.getId();
                IntegrationCouponWallet couponWallet = integrationCouponWalletSrv.caculateCoupon(null, integrationChannelId, mallId);
                IntegrationCashCouponWallet cashWallet = integrationCashCouponWalletSrv.caculateCash(null, integrationChannelId, mallId);
                if(cashWallet!=null){
                    Long totalNumCashWallet = mallCashCouponSrvImpl.queryTotalNumByChannelId(integrationChannelId);
                    cashWallet.setTotalNum(totalNumCashWallet==null?0l:totalNumCashWallet);
                }
                if(couponWallet!=null){
                    Long totalNumCouponWallet = merchantCouponRepository.queryTotalNum(integrationChannelId);
                    couponWallet.setTotalNum(totalNumCouponWallet==null?0l:totalNumCouponWallet);
                }
                channelDtoDto.setCashWallet(cashWallet);
                channelDtoDto.setCouponWallet(couponWallet);
//                channelDtoDto.setQuantity(quantity);
                return channelDtoDto;
            }).collect(Collectors.toList());
            List<IntegrationChannelDto> dtos = pageResult.data;
            mallCashCouponSrvImpl.exchange(response,dtos,mallId);
//            integrationCashCouponWalletSrv.exportExchangeCash(request,response,dto, mallId, Whether.NO);


        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/coupon/page M端 渠道兑换 优惠券列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} id <code>必选参数</code> 积分渠道id
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {Long} endTime 结束时间
     * @apiParam {String} faceValue 面额
     * @apiParam {String} exchangeCode 交换码
     * @apiParam {Long} batchPutNo 批次id
     * @apiSuccess {String} id 序号
     * @apiSuccess {String} exchangeCode 兑换码
     * @apiSuccess {String} exchangeDate 兑换时间
     * @apiSuccess {String} receiveDate 领取时间
     * @apiSuccess {String} faceValue 面值
     * @apiSuccess {String} merchantName 所属商户
     * @apiSuccess {String} batchPutNo 编号
     * @apiSuccess {String} flagCode 卡券标识码
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "id": 3,
     *         "dateCreated": "2016-12-28 15:37:13",
     *         "lastUpdated": "2016-12-28 15:50:24",
     *         "version": 0,
     *         "cashCouponId": 22,
     *         "faceValue": 50,
     *         "exchangeCode": "eb127622eb1276",
     *         "exchangeNum": 1,
     *         "receiveNum": 0,
     *         "useNum": 0,
     *         "exchangeDate": "2016-12-28 15:37:13",
     *         "integrationChannelId": 5,
     *         "mallId": 51,
     *         "batchPutNo": 3,
     *         "flagCode": 253234dsf4623
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10,
     *     "url": "/mall/integration/channel/cash/page",
     *     "prevUrl": "/mall/integration/channel/cash/page?pageNo=0&pageSize=10",
     *     "nextUrl": "/mall/integration/channel/cash/page?pageNo=0&pageSize=10"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_COUPON_DETAIL_PAGE, method = RequestMethod.GET)
    public JsonResult qrChannelCouponDetail(HttpServletRequest request, IntegrationChannelDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == dto.getId()) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            PageResult page = this.getPage(dto.getPageNo(), dto.getPageSize());
            PageResult<IntegrationCouponWalletDto> pageResult = integrationCouponWalletSrv.findChannelCouponDetail(dto, mallId, Whether.NO, page);
            pageResult.setUrl(Routes.MALL_INTEGRATION_CHANNEL_COUPON_DETAIL_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/cash/page M端 渠道兑换 现金券列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} id <code>必选参数</code> 积分渠道id
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {Long} endTime 结束时间
     * @apiParam {String} faceValue 面额
     * @apiParam {String} exchangeCode 交换码
     * @apiParam {Long} batchPutNo 批次id
     * @apiSuccess {String} id 序号
     * @apiSuccess {String} exchangeCode 兑换码
     * @apiSuccess {String} exchangeDate 兑换时间
     * @apiSuccess {String} receiveDate 领取时间
     * @apiSuccess {String} faceValue 面值
     * @apiSuccess {String} batchPutNo 编号
     * @apiSuccess {String} flagCode 卡券标识码
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "id": 3,
     *         "dateCreated": "2016-12-28 15:37:13",
     *         "lastUpdated": "2016-12-28 15:50:24",
     *         "version": 0,
     *         "cashCouponId": 22,
     *         "faceValue": 50,
     *         "exchangeCode": "eb127622eb1276",
     *         "exchangeNum": 1,
     *         "receiveNum": 0,
     *         "useNum": 0,
     *         "exchangeDate": "2016-12-28 15:37:13",
     *         "integrationChannelId": 5,
     *         "mallId": 51,
     *         "batchPutNo": 3,
     *         "flagCode": 253234dsf4623
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10,
     *     "url": "/mall/integration/channel/cash/page",
     *     "prevUrl": "/mall/integration/channel/cash/page?pageNo=0&pageSize=10",
     *     "nextUrl": "/mall/integration/channel/cash/page?pageNo=0&pageSize=10"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_CASH_DETAIL_PAGE, method = RequestMethod.GET)
    public JsonResult qrChannelCashDetail(HttpServletRequest request, IntegrationChannelDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == dto.getId()) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            PageResult page = this.getPage(dto.getPageNo(), dto.getPageSize());
            PageResult<IntegrationCashCouponWalletDto> pageResult = integrationCashCouponWalletSrv.findChannelCashDetail(dto, mallId, Whether.NO, page);
            pageResult.setUrl(Routes.MALL_INTEGRATION_CHANNEL_CASH_DETAIL_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/all/detail M端 渠道兑换 汇总
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} id <code>必选参数</code> 积分渠道id
     * @apiSuccess {String} exchangeNumCashAmount 已兑换现金券总金额
     * @apiSuccess {String} exchangeNumCouponAmount 已兑换优惠卡券总金额
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 5,
     *     "exchangeNumCashAmount": 3,
     *     "exchangeNumCashAmount": 10
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_ALL_DETAIL, method = RequestMethod.GET)
    public JsonResult channelAll(HttpServletRequest request, IntegrationChannelDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == dto) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            if (null == dto.getId()) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
//            Long exchangeNumCash= integrationCashCouponWalletSrv.qrExchangeNumByChannelId(dto, mallId, Whether.NO);
//            Long exchangeNumCoupon= integrationCouponWalletSrv.qrExchangeNumByChannelId(dto, mallId, Whether.NO);
            IntegrationChannel integrationChannel = integrationChannelSrv.findOne(dto.getId());
            dto.setName(integrationChannel.getName());
//            dto.setExchangeNumCash(exchangeNumCash);
//            dto.setExchangeNumCoupon(exchangeNumCoupon);
            Double exchangeNumCashAmount = integrationCashCouponWalletSrv.qrExchangeNumCashAmountByChannelId(dto, mallId, Whether.NO);
            Double exchangeNumCouponAmount = integrationCouponWalletSrv.qrExchangeNumCouponAmountByChannelId(dto, mallId, Whether.NO);
            dto.setExchangeNumCashAmount(exchangeNumCashAmount);
            dto.setExchangeNumCouponAmount(exchangeNumCouponAmount);
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/export/exchange/coupon M端 导出渠道优惠券兑换详细 列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必选参数</code> 积分渠道id
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {String} faceValue 面额
     * @apiParam {String} exchangeCode 交换码
     * @apiParam {Long} batchNo 批次id
     * @apiParam {String[]} titles 表格标题数组
     * @apiSuccessExample {json} Success-Response:
     * {}
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_EXPORT_EXCHANGE_COUPON, method = RequestMethod.GET)
    public JsonResult exportExchangeCoupon(HttpServletRequest request, HttpServletResponse response,IntegrationChannelDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == dto) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            if (null == dto.getId()) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            integrationCouponWalletSrv.exportExchangeCoupon(request,response,dto, mallId, Whether.NO);
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/channel/export/exchange/cash M端 导出渠道现金券兑换详细 列表
     * @apiGroup INTEGRATION_CHANNEL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必选参数</code> 积分渠道id
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {String} faceValue 面额
     * @apiParam {String} exchangeCode 交换码
     * @apiParam {Long} batchNo 批次id
     * @apiParam {String[]} titles 表格标题数组
     * @apiSuccessExample {json} Success-Response:
     * {}
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CHANNEL_EXPORT_EXCHANGE_CASH, method = RequestMethod.GET)
    public JsonResult exportExchangeCash(HttpServletRequest request, HttpServletResponse response,IntegrationChannelDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == dto) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            if (null == dto.getId()) {
                jsonResult.remind("渠道id不能为空",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            integrationCashCouponWalletSrv.exportExchangeCash(request,response,dto, mallId, Whether.NO);
        };
        return doing.go(request, log);
    }


}
